<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 警告组件 -->
      <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon></el-alert>
      <span>选择商品分类:</span>
      <!-- 级联选择器 -->
      <el-cascader
        v-model="selectedCateId"
        :options="cateList"
        :props="cascaderprop"
        @change="handleChange"
      ></el-cascader>

      <!-- tab切换的组件 -->

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="idDisable"
            @click="AddDialogVisible=true"
          >添加参数</el-button>
          <!-- 表格插件 -->
          <el-table :data="manyDate" border style="width: 100%">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scoped">
                <!-- start  动态标签 -->
                <el-tag
                  :key="index"
                  v-for="(tag,index) in scoped.row.attr_vals"
                  closable
                  :disable-transitions="true"
                  @close="handleClose(scoped.row,index)"
                >{{tag}}</el-tag>
                <!-- 文本输入框 -->
                <el-input
                  class="input-new-tag"
                  v-if="inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <!-- 按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
                <!-- end  动态标签 -->
              </template>
            </el-table-column>
            <el-table-column type="index" width="80"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParamsId(scoped.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParmas(scoped.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="idDisable"
            @click="AddDialogVisible=true"
          >添加属性</el-button>
          <!-- 表格插件 -->
          <el-table :data="onlyDate" border style="width: 100%">
            <el-table-column type="expand"></el-table-column>
            <el-table-column type="index" width="80"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="editParamsId(scoped.row.attr_id)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="deleteParmas(scoped.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 添加的对话框 -->
      <el-dialog
        :title="activeName==='many'?'添加动态参数':'添加静态属性'"
        :visible.sync="AddDialogVisible"
        width="40%"
      >
        <!-- 表单插件 -->
        <el-form :model="AddForm" :rules="AddFormRules" ref="AddFormRef" label-width="100px">
          <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="AddForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="AddDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addparams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑的对话框 -->

      <el-dialog
        :title="activeName==='many'?'修改动态参数':'修改静态属性'"
        :visible.sync="editDialogVisible"
        width="40%"
      >
        <!-- 表单插件 -->
        <el-form :model="EditForm" :rules="AddFormRules" ref="EditFormRef" label-width="100px">
          <el-form-item :label="activeName==='many'?'动态参数':'静态属性'" prop="attr_name">
            <el-input v-model="EditForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParmas">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { truncate } from "fs";
export default {
  data() {
    return {
      // 所有商品分类列表
      cateList: [],
      // 选中的所有分类的id
      selectedCateId: [],
      cascaderprop: {
        value: "cat_id",
        label: "cat_name",
        children: "children"
      },
      activeName: "many",
      //   动态参数数据
      manyDate: [],
      //静态参数数据
      onlyDate: [],
      // 添加的弹框
      AddDialogVisible: false,
      // 添加表单的校验规则
      AddFormRules: {
        attr_name: [
          { required: true, message: "请添加参数名称", trigger: "blur" }
        ]
      },
      AddForm: {
        // 添加参数的名称
        attr_name: ""
      },
      // 编辑表单
      editDialogVisible: false,
      EditForm: {
        // 编辑参数的名称
        attr_name: ""
      },
      // 控制文本框的显示隐藏
      inputVisible: false,
      inputValue: ""
    };
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 3 }
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取商品分类失败");
      }

      this.cateList = res.data;
      console.log(this.cateList);
    },
    // 只要输入框的值改变会触发这个事件
    async handleChange() {
      // console.log(this.selectedCateId)
      //如果用户选中的不是三级列表那么就清空数组
      if (this.selectedCateId.length !== 3) {
        this.selectedCateId = [];
        this.manyDate = [];
        this.onlyDate = [];
      } else {
        this.getTableDate();
      }
    },
    // 获取表格的数据
    async getTableDate() {
      // 用户选中的是三级列表
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        { params: { sel: this.activeName } }
      );
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取数据失败");

      // // 拿到res.data中的数据 attr_vals是个字符串用split切割成数组
      res.data.forEach(item => {
        const arr =item.attr_vals? item.attr_vals.split(" "):[]
    
        item.attr_vals = arr;
      });
      if (this.activeName === "many") {
        this.manyDate = res.data;
        console.log("以下是三级列表的数据");
        // console.log(this.manyDate)
      } else {
        this.onlyDate = res.data;
      }
      console.log(res);
    },
    handleClick() {
      if (!this.cateId) return;
      this.getTableDate();
    },
    // 添加的方法
    addparams() {
      this.$refs.AddFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          { attr_name: this.AddForm.attr_name, attr_sel: this.activeName }
        );
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.errot("创建失败");
        }
        this.AddDialogVisible = false;
        this.getTableDate();
      });
    },
    // 编辑的方法
    async editParamsId(id) {
      this.editDialogVisible = true;
      // 发起请求
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        { params: { sel: this.activeName } }
      );
      console.log("以下是根据id 获取的整条数据");
      console.log(res);
      // 把获取的数据回显在表单中
      this.EditForm = res.data;
    },
    // 点击确定更改
    editParmas() {
      this.$refs["EditFormRef"].validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.EditForm.attr_id}`,
          { attr_name: this.EditForm.attr_name, attr_sel: this.activeName }
        );
        console.log("以下是点击确定修改的数据");
        console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error("更新失败");
        }
        this.$message.success("更新成功");
        this.getTableDate();
        this.editDialogVisible = false;
      });
    },
    // 删除的方法
    deleteParmas(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          );
          this.getTableDate();
          console.log(res);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 每当文本框失去焦点的时候 按下了enter 触发这个函数
    async handleInputConfirm(row) {
      if (this.inputValue.trim().length === 0) {
        this.inputValue = "";
        this.inputVisible = false;
        return false;
      }
      if (this.inputValue.trim().length > 0) {
        row.attr_vals.push(this.inputValue);
        // 输入框为空
        this.inputValue = ""; 
      }
      this.inputVisible = false;
      // 输入框为空
      this.inputValue = "";

      //发起请求
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          // 因为服务器是字符串 目前是数组 转换下
          attr_vals: row.attr_vals.join(" "),
          attr_sel: row.attr_sel
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更改参数失败");
      }
    },
    // 点击按钮 显示文本框
    showInput() {
      this.inputVisible = true;
      // 当页面上的元素重新渲染的时候 会执行回调函数
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 删除tag标签
    async handleClose(row, index) {
      row.attr_vals.splice(index, 1);
      //发起请求
      const { data: res } = await this.$http.put(
        `categories/${row.cat_id}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          // 因为服务器是字符串 目前是数组 转换下
          attr_vals: row.attr_vals.join(" "),
          attr_sel: row.attr_sel
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("更改参数失败");
      }
    }
  },

  created() {
    this.getCateList();
  },
  //   计算属性
  computed: {
    //   如果被选中的id长度为3 添加那就禁用
    idDisable: function() {
      if (this.selectedCateId.length == 3) return false;
      return true;
    },
    //判断选中的是不是三级列表
    cateId: function() {
      if (this.selectedCateId.length === 3) return this.selectedCateId[2];
      return null;
    }
  }
};
</script>


<style lang="less" scoped>
.el-card {
  margin-top: 10px;
}
span,
.el-cascader {
  margin-right: 15px;
  margin-top: 20px;
}
.el-table {
  margin-top: 15px;
}
.el-tag {
  margin: 10px 10px;
}
.input-new-tag {
  width: 150px;
}
</style>

